<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_fetcSoftwareList"
    :columns="columns"
    row-key="id"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="version:upgrade:add"
          >新增</b-button
        >
        <b-button
          icon="delete"
          @click="onDelete()"
          code="version:upgrade:remove"
          :disabled="!selectRows.length"
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        icon="detail"
        type="link"
        @click="onLook(record)"
        code="version:upgrade:show"
      >
        查看</b-button
      >
      <span v-if="record.isAudit == '1'">
        <!-- <b-button
          icon="edit"
          type="link"
          @click="onUpdate(record)"
          code="version:upgrade:edit"
        >
          编辑</b-button
        > -->
        <b-button
          icon="examine"
          type="link"
          @click="onAudit(record)"
          code="version:upgrade:audit"
        >
          审核</b-button
        >
      </span>
      <span v-else>
        <b-button
          icon="remote"
          type="link"
          @click="onPush(record)"
          code="version:upgrade:pushTotalLog:add"
        >
          推送</b-button
        >
        <b-button
          icon="detail"
          type="link"
          @click="onRecord(record)"
          code="version:upgrade:pushTotalLog:query"
        >
          记录</b-button
        >
      </span>
    </template>
  </ProTable>
  <Modal
    v-if="openAudit"
    v-model:open="openAudit"
    :title="title"
    :width="1200"
    :mask-closable="false"
    centered
    destroy-on-close
    wrap-class-name="task-modal"
  >
    <Add
      :taskInfo="taskInfo"
      ref="addRef"
      key="addRef"
      @versionUpdate="pushUpdate"
      v-if="modalType === 'add' || modalType === 'edit'"
    ></Add>

    <Audit
      ref="auditRef"
      :audit="auditInfo"
      @versionAudit="colseAudit"
      key="auditRef"
      v-if="modalType === 'info' || modalType === 'audit'"
    ></Audit>

    <template #footer>
      <div v-if="modalType === 'info' && auditInfo.isAudit !== '0'">
        <b-button type="primary" @click="onEdit" code="version:upgrade:edit"
          >编 辑</b-button
        >
      </div>
      <div v-if="modalType === 'audit'">
        <b-button type="primary" @click="onAuditConfirm">通 过</b-button>
      </div>
      <div v-if="modalType === 'add' || modalType === 'edit'">
        <b-button type="primary" @click="onConfirm">提 交</b-button>
        <b-button @click="onCancel">取 消</b-button>
      </div>
    </template>
  </Modal>

  <Modal
    v-model:open="openPush"
    title="推送"
    :width="1200"
    :mask-closable="false"
    centered
    destroy-on-close
    :footer="null"
    wrap-class-name="push-modal"
  >
    <!-- ref="verifyRef" :push="pushInfo" @pushUpdate="updateLog" -->
    <Push :push="pushInfo" ref="pushRef" @pushUpdate="updateLog"></Push>
  </Modal>
  <Modal
    v-model:open="openUpdate"
    title="推送设备列表"
    :width="1200"
    :mask-closable="false"
    centered
    :footer="null"
    destroy-on-close
  >
    <Update :update="updateInfo"></Update>
  </Modal>
  <Modal
    v-model:open="openRecord"
    title="推送记录"
    :width="1200"
    :mask-closable="false"
    centered
    :footer="null"
    destroy-on-close
  >
    <Record :log="logInfo" @closeRecord="closeRecord"></Record>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, nextTick, onMounted, provide, ref } from 'vue';
import {
  Col,
  Input,
  Modal,
  Row,
  Space,
  Tag,
  Tree,
  TreeProps,
  message,
} from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToOption } from '@/utils/utils';
import {
  appUpdateTypeEnum,
  appUpdateTypeOption,
  auditEnum,
  packageTypeEnum,
} from '@/constant/push';
import { getUpgradeDetail, modelTree, pullPackageList } from '@/api/config';
import {
  deletesendVersion,
  getVersionlist,
  sendVersionDetail,
  sendVersionInfo,
} from '@/api/push';
import Add from './components/Add.vue';
import Audit from './components/Audit.vue';
import Push from './components/Push.vue';
import Record from './components/Record.vue';
import Update from './components/Update.vue';

provide('page', 'upgradeTasks');
const tableRef = ref();
const handleState = ref('0');
const _fetcSoftwareList = async (params: any) => {
  const res = await getVersionlist({
    ...params,
    isEnable: handleState.value,
  });
  res.rows.forEach((item: any) => {
    if (item.modelAlwaysVOS) {
      item.modelAlwaysVOS.forEach((model: any) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name: any) => {
          return {
            typeName: name,
          };
        });
      });
    }
  });
  return { rows: [...res.rows], total: res.total || 0 };
};

const fileNames: TreeProps['fieldNames'] = {
  title: 'typeName',
  children: 'modeName',
};

const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});

const modelTreeData = ref([]);
const packgaeList = ref<{ label: string; value: string | number }[]>([]);
onMounted(() => {
  modelTree().then((res: any) => {
    modelTreeData.value = res.data;
  });
  pullPackageList({ deviceType: '1' }).then((res: any) => {
    packgaeList.value = listToOption(res.data, 'name', 'id');
  });
});
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '版本类型',
    dataIndex: 'deviceType',
    valueEnum: packageTypeEnum,
    fixed: 'left',
  },
  {
    title: '版本ID',
    dataIndex: 'code',
    fixed: 'left',
  },
  {
    title: '包版本',
    dataIndex: 'version',
    fixed: 'left',
  },
  {
    title: '更新类型',
    dataIndex: 'appUpdateType',
    valueEnum: appUpdateTypeEnum,
    width: 100,
    customRender({ text }) {
      return (
        <Tag class={text == '1' ? 'ql' : 'zl'}>
          {appUpdateTypeEnum[text as keyof typeof appUpdateTypeEnum]}
        </Tag>
      );
    },
    fixed: 'left',
  },
  {
    title: '升级计划说明',
    dataIndex: 'versionDesc',
    hideInSearch: true,
  },
  {
    title: '设备数',
    dataIndex: 'num',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '审核状态',
    dataIndex: 'isAudit',
    valueEnum: auditEnum,
    width: 100,
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'success' : 'warning'}>
          {auditEnum[text as keyof typeof auditEnum]}
        </Tag>
      );
    },
  },
  {
    title: '审核时间',
    dataIndex: 'auditTime',
    hideInSearch: true,
  },
  {
    title: '审核人',
    dataIndex: 'auditBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 300,
  },
]);

const openAdd = ref(false);
const modalType = ref('info');
const onAdd = async () => {
  openAudit.value = true;
  title.value = '新增';
  modalType.value = 'add';
  taskInfo.value = {};
};
const taskInfo = ref({});
const onUpdate = async (record: any) => {
  openAdd.value = true;
  title.value = '编辑';
  sendVersionInfo(record.id).then((res: any) => {
    console.log(res);
    if (res.data.modelAlwaysVOS) {
      res.data.modelAlwaysVOS.forEach((model) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name) => {
          return {
            typeName: name,
          };
        });
      });
    }
    taskInfo.value = res.data;
  });
};

const onEdit = async () => {
  title.value = '编辑';
  modalType.value = 'edit';
  nextTick(() => {
    taskInfo.value = cloneDeep(cloneInfo.value);
  });
};

const openAudit = ref(false);
const auditInfo = ref({});
const title = ref('');
const onAudit = async (record: any) => {
  openAudit.value = true;
  title.value = '审核';
  modalType.value = 'audit';
  sendVersionInfo(record.id).then((res: any) => {
    if (res.data.modelAlwaysVOS) {
      res.data.modelAlwaysVOS.forEach((model) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name) => {
          return {
            typeName: name,
          };
        });
      });
    }
    if (res.data.projectDeviceGroupMap) {
      res.data.projectDeviceGroupMap.forEach((item: any) => {
        if (item.modelAlwaysVOS) {
          item.modelAlwaysVOS.forEach((model: any) => {
            model.typeName = `${model.typeName}(${model.modeName.length})`;
            model.modeName = model.modeName.map((name: any) => {
              return {
                typeName: name,
              };
            });
          });
        }
      });
    }
    auditInfo.value = res.data;
    console.log(auditInfo.value, 'auditInfo');
  });
};
const auditRef = ref();
const onAuditConfirm = async () => {
  auditRef.value.onConfirm();
};
const colseAudit = () => {
  openAudit.value = false;
  tableRef.value.refresh();
};
const pushInfo = ref({});
const pushRef = ref();
const addRef = ref();
const onConfirm = async () => {
  addRef.value.submitForm();
};
const pushUpdate = () => {
  tableRef.value.refresh();
  openAudit.value = false;
};
const cloneInfo = ref({});
const onLook = async (record: any) => {
  title.value = '查看';
  modalType.value = 'info';
  openAudit.value = true;
  sendVersionInfo(record.id).then((res: any) => {
    console.log(res, '12323');
    if (res.data.modelAlwaysVOS) {
      res.data.modelAlwaysVOS.forEach((model) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name) => {
          return {
            typeName: name,
          };
        });
      });
    }
    if (res.data.sendType == '2') {
      res.data.projectDeviceGroupMap.forEach((item: any) => {
        if (item.modelAlwaysVOS) {
          item.modelAlwaysVOS.forEach((model: any) => {
            model.typeName = `${model.typeName}(${model.modeName.length})`;
            model.modeName = model.modeName.map((name: any) => {
              return {
                typeName: name,
              };
            });
          });
        }
      });
    }
    auditInfo.value = res.data;
    cloneInfo.value = cloneDeep(res.data);
    console.log(auditInfo.value, 'auditInfo');
  });
};

const openPush = ref(false);
const onPush = async (record: any) => {
  sendVersionDetail(record.id).then((res: any) => {
    pushInfo.value = res.data;
  });
  openPush.value = true;
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async () => {
  const ids = selectRows.value.map((item) => item.id);
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认删除当前项？`,
    onOk: async () => {
      await deletesendVersion(ids.join());
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};

const verifyRef = ref();
const onVerify = async () => {
  verifyRef.value.submitForm();
};

const openUpdate = ref(false);
const updateInfo = ref({});
const updateLog = (data: any) => {
  updateInfo.value = data;
  openUpdate.value = true;
};

const openRecord = ref(false);
const logInfo = ref({});
const onRecord = async (record: any) => {
  openRecord.value = true;
  logInfo.value = record;
};
const closeRecord = (data: any) => {
  updateInfo.value = data;
  openUpdate.value = true;
};
const onCancel = () => {
  modalType.value = 'info';
  title.value = '查看';
  nextTick(() => {
    auditInfo.value = cloneDeep(cloneInfo.value);
  });
};
</script>
<style lang="scss">
.task-modal {
  .ant-modal-body {
    min-height: 70vh;
    padding: 0 24px !important;
  }
}
</style>
